import TPagination from 't/basic/pagination';
import TInput from 't/basic/input';
import TSelect from 't/basic/select';

import QSelect from '@teld/q-components/Select';

import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  pickOwnForBasicComponent,
  usePropsTwoWayValues,
  zipFasDynamicFilter,
  filter2FasDynamicFilter,
} from 't/common/utils';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  toRef,
  watch,
} from 'vue';

import { useI18n } from 'vue-i18n';
import { debounce, dom, useQuasar } from '@teld/q-components';

import './Pagination.scss';

export const C_Prefab = {
  Default: 'default',
  Simple: 'simple',
  Perfective: 'perfective',
  Mobile: 'mobile',
};

export const paginationProps = {
  prefab: {
    type: String,
    default() {
      return C_Prefab.Default;
    },
  },
  pageSizeRange: {
    type: Array,
    default() {
      return [10, 20, 30, 40];
    },
  },
  totals: {
    type: Number,
    default() {
      return void 0;
    },
  },
  pageSize: {
    type: Number,
    default() {
      return 10;
    },
  },
  maxPages: {
    type: Number,
    default() {
      return 6;
    },
  }
};

export default defineComponent({
  name: 'TPrefabPagination',
  props: {
    ...commonProps,
    ...TPagination.props,
    ...paginationProps,
  },
  emits: [...TPagination.emits, 'pageSizeChanged', 'pageChanged'],

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();
    const { t } = useI18n({ useScope: 'global' });

    const [mappingProps, mappingExpose] = useMappingProps(props);

    expose(mappingExpose);

    onMounted(() => {});

    const simpleProps = reactive({
      input: true,
      inputStyle: 'color:rgba(0,0,0,0.8)',
      iconFirst: 'none',
      iconLast: 'none',
      maxPages: '3',
      directionLinks: true,
    });

    function renderSimplePagination(extendProps = simpleProps) {
      return renderPagination(extendProps);
    }

    function getTotalInfo() {
      const totalLang = getLang('total', '共 {{total}} 条');
      return totalLang.replace(/{{total}}/g, mappingProps.totals);
    }

    const computedTotalInfo = computed(() => {
      return getTotalInfo();
    });

    const computedMax = computed(() => {
      let max = mappingProps.max;
      if (void 0 !== mappingProps.totals) {
        max = Math.ceil(mappingProps.totals / mappingProps.pageSize);
      }
      return max;
    });

    const inputEvents = computed(() => {
      let value;
      function updateModel(value) {
        const page = parseInt(value, 10);
        if (page >= mappingProps.min && page <= computedMax.value)
          currentPage.value = page;
      }
      return {
        'onUpdate:modelValue': val => {
          value = val;
        },
        'onKeyup': evt => {
          evt.keyCode === 13 && updateModel(value);
        },
        'onBlur': () => {
          updateModel(value);
        },
      };
    });

    function getLang(langKey, defaultVal = '') {
      return $q.lang?.prefabPagination?.[langKey] || defaultVal;
    }

    function renderJump() {
      return (
        <>
          <span class='jump-title'>{getLang('jump')}</span>
          <div class='jump-input'>
            <TInput
              type='number'
              dense
              borderless
              modelValue={currentPage.value}
              min={1}
              max={computedMax.value}
              {...inputEvents.value}
            ></TInput>
          </div>
        </>
      );
    }

    function renderPerfectivePagination(
      extendProps = {
        maxPages: mappingProps.maxPages||6,
        directionLinks: true,
        ellipses: true,
        boundaryNumbers: true,
      },
    ) {
      const clsPrefix = `${cls}__perfective`;
      return (
        <div class={[clsPrefix]}>
          <div class={[`${clsPrefix}-total`]}>{computedTotalInfo.value}</div>
          <div class={[`${clsPrefix}-pagination`]}>
            {renderPagination(extendProps)}
          </div>
          <div class={[`${clsPrefix}-page-size`]}>
            <QSelect
              dropdown-icon={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`}
              v-model={mappingProps.pageSize}
              borderless
              onUpdate:modelValue={ps => {
                emit('update:pageSize', ps);
                emit('pageSizeChanged', ps);
              }}
              options={mappingProps.pageSizeRange}
            >
              {{
                selected: () => (
                  <div>
                    <span class='page-size-val'>{mappingProps.pageSize}</span>
                    <span class='page-size-val-suffix'>
                      {getLang('pageSize', '条/页')}
                    </span>
                  </div>
                ),
              }}
            </QSelect>
          </div>
          <div class={[`${clsPrefix}-jump`]}>{renderJump()}</div>
        </div>
      );
    }

    function renderMobilePagination(
      extendProps = {
        maxPages: 4,
        directionLinks: true,
        ellipses: true,
        boundaryNumbers: true,
      },
    ) {
      const clsPrefix = `${cls}__perfective`;
      return (
        <div class={[clsPrefix, 'mobile']}>
          <div class={[`${clsPrefix}-pagination`]}>
            {renderPagination(extendProps)}
          </div>
        </div>
      );
    }

    const currentPage = computed({
      get: () => props.modelValue,
      set: val => {
        emit('update:modelValue', val);
      },
    });

    function renderPagination(extendProps = {}) {
      return (
        <TPagination
          {...attrs}
          {...pickOwnForBasicComponent(mappingProps, TPagination.props, attrs)}
          {...extendProps}
          v-model={currentPage.value}
          max={computedMax.value}
          onUpdate:modelValue={page => {
            emit('pageChanged', page);
          }}
          // maxPages={extendProps.maxPages}
          // // v-model={computedPagination.value.page}
          // input
          // input-style='color:rgba(0,0,0,0.8)'
          // icon-first='none'
          // icon-last='none'
          // max-pages='3'
          // direction-links
          // max={computedMax.value}
        />
      );
    }

    function renderFactory() {
      let renderFunc = renderPagination;
      switch (props.prefab) {
        case C_Prefab.Simple:
          renderFunc = renderSimplePagination();
          break;
        case C_Prefab.Perfective:
          renderFunc = renderPerfectivePagination();
          break;
        case C_Prefab.Mobile:
          renderFunc = renderMobilePagination();
          break;
        default:
          return renderPagination();
      }
      return renderFunc;
    }

    const cls = 't-prefab-pagination';

    return () => {
      return mappingProps.visible && <div class={[cls]}>{renderFactory()}</div>;
    };
  },
});
